from sqlalchemy.orm import Session
from . import schema
from .models import User  # 导入用户模型类
from sqlalchemy import func


# 查询所有用户信息
def get_all_users(db: Session):
    return db.query(User).all()


# 通过用户ID查询（修复参数名错误）
def get_id_user(db: Session, user_id: int):
    return db.query(User).filter(User.id == user_id).first()


# 通过用户名查询（修复返回类型，补充all()）
def get_name_user(db: Session, username: str):
    return db.query(User).filter(User.username == username).all()


# 添加新用户（修复参数类型注解）
def add_user(db: Session, user_schema: schema.CreateUser):
    # 使用Pydantic V2的model_dump()方法代替dict()
    db_user = User(**user_schema.model_dump())
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user


# 修改用户信息（修复筛选条件变量名错误）
def mod_user(db: Session, user_id: int, mod_schema: schema.UpdateUser):
    db_user = db.query(User).filter(User.id == user_id).first()
    if not db_user:
        return None
    # 只更新非空字段
    update_data = mod_schema.dict(exclude_unset=True)
    for key, value in update_data.items():
        setattr(db_user, key, value)
    db.commit()
    db.refresh(db_user)
    return db_user


# 多条件筛选查询（修复id参数判断错误）
def get_by_filters(
    db: Session,
    user_id: int = None,
    username: str = None,
    real_name: str = None
):
    query = db.query(User)
    if user_id:  # 修复原代码的if id:错误
        query = query.filter(User.id == user_id)
    if username:
        query = query.filter(User.username == username)
    if real_name:
        query = query.filter(User.real_name == real_name)
    return query.all()


# 新增：通过ID删除用户
def delete_user(db: Session, user_id: int):
    db_user = db.query(User).filter(User.id == user_id).first()
    if not db_user:
        return None
    db.delete(db_user)
    db.commit()
    return True  # 返回删除成功标志